//
//  YunGridVC.swift
//  YunChenCalculator
//
//  Created by Li Dong on 2023/10/16.
//

import UIKit
import SnapKit

class YunGridVC: YunBaseVC {
    
    private let CellID = NSStringFromClass(YunGridCell.self)
    private var collectionView: UICollectionView!
    private var numberList = [YunGridModel]()
    private var clickNumber = 0
    private var seconds = 0
    var timer: Timer?

    override func viewDidLoad() {
        super.viewDidLoad()

        title = "舒尔特方格注意力测试"
        view.backgroundColor = .init(hex: 0xE0FFD1)
        initCollectionView()
        configNumbers()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        destoryTimer()
    }
    
    private func initCollectionView() {
        let itemW = (CGFloat.screenWidth-62)/4
        
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .vertical
        layout.minimumLineSpacing = 3
        layout.minimumInteritemSpacing = 3
        layout.itemSize = CGSize(width: itemW, height: itemW)
        
        collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.backgroundColor = .clear
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.register(UINib(nibName: "YunGridCell", bundle: nil), forCellWithReuseIdentifier: CellID)
        view.addSubview(collectionView)
        collectionView.snp.makeConstraints { make in
            make.top.equalTo(50)
            make.left.equalTo(25)
            make.right.equalTo(-25)
            make.height.equalTo(collectionView.snp.width)
        }
    }
    
    private func configNumbers() {
        clickNumber = 0
        seconds = 0
        if !numberList.isEmpty {
            numberList.removeAll()
        }
        var numbers = [Int]()
        for i in 1...16 {
            numbers.append(i)
        }
        while !numbers.isEmpty {
            let randomNumber = Int(arc4random_uniform(UInt32(numbers.count)))
            numberList.append(YunGridModel(number: "\(numbers[randomNumber])", isSelect: false))
            numbers.remove(at: randomNumber)
        }
        collectionView.reloadData()
    }
    
    private func showAlert(title: String, subTitle: String) {
        let alert = YunGrideAlert(frame: view.window!.screen.bounds)
        alert.title = title
        alert.subTitle = subTitle
        alert.callBack = {[weak self] in
            self?.configNumbers()
        }
        UIApplication.shared.windows.first?.addSubview(alert)
    }
    
    
    private func startTimer() {
        if timer == nil {
            timer = Timer(timeInterval: 1, target: self, selector: #selector(timerHandler), userInfo: nil, repeats: true)
            RunLoop.main.add(timer!, forMode: .common)
        }
    }
    
    @objc private func timerHandler() {
        seconds += 1
    }

    private func destoryTimer() {
        if timer != nil {
            timer?.invalidate()
            timer = nil
        }
    }
}

extension YunGridVC: UICollectionViewDelegate, UICollectionViewDataSource {
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        numberList.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CellID, for: indexPath) as! YunGridCell
        cell.model = numberList[indexPath.row]
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        var model = numberList[indexPath.row]
        if model.isSelect {
            return
        }
        model.isSelect = true
        numberList[indexPath.row] = model
        collectionView.reloadData()
        clickNumber += 1
        if clickNumber == 1 {
            startTimer()
        }
        if clickNumber != Int(model.number) {
            destoryTimer()
            showAlert(title: "WRONG", subTitle: "预期是\(clickNumber)，但你点击了\(model.number)")
        }else if clickNumber == numberList.count {
            destoryTimer()
            if seconds <= 16 {
                showAlert(title: "Congratulations", subTitle: "完成！你一共花费了\(seconds)秒，\n优秀！")
            }else{
                showAlert(title: "Congratulations", subTitle: "完成！你一共花费了\(seconds)秒，\n还可以更好！")
            }
        }
    }
}

struct YunGridModel  {
    var number: String
    var isSelect: Bool
    
}
